package com.liugh.service.zhongche.Imp;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.liugh.base.BusinessException;
import com.liugh.base.PublicResultConstant;
import com.liugh.entity.User;
import com.liugh.entity.standard.StandardApprove;
import com.liugh.entity.standard.StandardItem;
import com.liugh.enums.zhongche.ApproveEnum;
import com.liugh.mapper.zhongche.StandardApproveMapper;
import com.liugh.mapper.zhongche.StandardItemMapper;
import com.liugh.service.IUserService;
import com.liugh.service.zhongche.IESModelService;
import com.liugh.service.zhongche.IStandardApproveService;
import com.liugh.service.zhongche.IStandardService;
import com.liugh.util.CommonUtil;
import com.liugh.util.PDFToImage;
import org.csource.common.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**标准审批 .
 * Created by Fatao on 2018/10/30 .
 */
@Service

//开启事务
@EnableTransactionManagement(proxyTargetClass = true)
public class StandardApproveServiceImpl extends ServiceImpl<StandardApproveMapper, StandardApprove> implements IStandardApproveService {

    private static Logger Logger = LoggerFactory.getLogger(StandardApproveServiceImpl.class);

    //PDF转img以后的暂存存储路径
    private static String IMGPATH;

    @Value("${PdfToimgTempPath}")
    public void setIMGPATH(String imgpath) {
        StandardApproveServiceImpl.IMGPATH = imgpath;
    }

    @Autowired
    private StandardApproveMapper standardApproveMapper;

    @Autowired
    StandardItemMapper itemMapper;

    @Autowired
    StandPageServiceImpl pageService;


    @Autowired
    private IUserService userService;


    @Autowired
    private IStandardService standardItemService;


    @Autowired
    IESModelService modelService;

    /**
     * 撤销申请 .
     * @param id .
     * @return .
     */
    public int cancelApprove(int id) {
        return standardApproveMapper.deleteById(id);
    }

    /**
     * 驳回申请 .
     * @param standardApprove .
     * @return .
     */
    @Transactional
    public StandardApprove disagreeApprove(StandardApprove standardApprove) throws BusinessException {
        standardApprove.setStatus(ApproveEnum.DISAGREE_APPROVE.getCode());
        int result = standardApproveMapper.updateById(standardApprove);
        int result1 = itemMapper.deleteById(standardApprove.getStandardItemId());
        if (result <= 0 || result1 <= 0) {
            throw new BusinessException(PublicResultConstant.ERROR);
        }
        return standardApprove;
    }

    /**
     * 根据id获取申请 .
     * @param id .
     * @return .
     */
    public StandardApprove getApproveById(int id) {
        return standardApproveMapper.selectById(id);
    }

    /**
     * 获取我的申请 .
     *
     * @param userNo .
     * @return .
     */
    public Page<StandardApprove> getMyApprove(Page<StandardApprove> page, String userNo) {
       List<StandardApprove> approves =  standardApproveMapper.selectPage(page,new EntityWrapper<StandardApprove>().where("user_no = {0}",userNo).orderBy("apply_time",false));
        for (StandardApprove standardApprove : approves) {
            standardApprove.setApplyUserName(userService.getUserByUserNo(standardApprove.getUserNo()).getUsername());
            standardApprove.setStandardItemNo(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandNo());
            standardApprove.setStandardItemName(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandName());
            if (standardApprove.getApproveUserNo() != null) {
                standardApprove.setApproveUserName(userService.getUserByUserNo(standardApprove.getApproveUserNo()).getUsername());

            }
        }
       page.setRecords(approves);
       return page;
    }

    /**
     * 修改申请内容 .
     * @param standardApprove .
     * @return .
     */
    public StandardApprove updateApprove(StandardApprove standardApprove) {
        Integer result = standardApproveMapper.update(standardApprove,new EntityWrapper<StandardApprove>().where("id = {0}",standardApprove.getId()));
        return result > 0 ? standardApprove : null;
    }

    /**
     * 获取我批准的申请 .
     * @param user .
     * @param page .
     * @return .
     */
    public Page<StandardApprove> getAgreeApprove(User user, Page<StandardApprove> page) {
        List<StandardApprove> standardApproveList = standardApproveMapper.selectPage(page,new EntityWrapper<StandardApprove>()
                                                                    .eq("approve_user_no", user.getUserNo()).and()
                                                                    .eq("status",ApproveEnum.AGREE_APPROVE.getCode()).orderBy("apply_time",false));

        for (StandardApprove standardApprove : standardApproveList) {
            standardApprove.setApplyUserName(userService.getUserByUserNo(standardApprove.getUserNo()).getUsername());
            standardApprove.setStandardItemNo(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandNo());
            standardApprove.setStandardItemName(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandName());
            if (standardApprove.getUserNo() != null) {
                standardApprove.setApplyUserName(userService.getUserByUserNo(standardApprove.getApproveUserNo()).getUsername());
            }
        }
        return standardApproveList.isEmpty() ? null : page.setRecords(standardApproveList);
    }

    /**
     * 处理审批请求
     * @param approve
     * @throws IOException
     * @throws MyException
     */
    @Override
    @Transactional
    public void handleApprove(StandardApprove approve) throws Exception {

        Logger.info("=============开始碎片化==========");
        StandardItem item = itemMapper.selectById(approve.getStandardItemId());

        String fileUrl = item.getUploadDir();
        String suffix = FileUtil.extName(fileUrl);

        if ("pdf".equals(suffix) || "PDF".equals(suffix)) {
            //PDF转img,list存放toImg以后图片的地址
            List<String> list = pdfToImgHandle(new URL(fileUrl),item.getStandName());

            //将碎片化以后的文件上传
            pageService.handleSegment(list, item.getId(), item.getStandName(),IMGPATH);

            //更改状态为已同意
            approve.setAgreeTime(new Date());
            approve.setStatus(ApproveEnum.AGREE_APPROVE.getCode());
//            approve.setApproveUserNo(getUserByAppId(approve.getId()).getUserNo());
            standardApproveMapper.update(approve, new EntityWrapper<StandardApprove>().where("id = {0}", approve.getId()));

            //同步更新item表
            synUpdateItem(item.getId(),ApproveEnum.AGREE_APPROVE.getCode());

            //加入ES索引
            modelService.addESModel(item.getId());

        } else {
            synUpdateItem(item.getId(),ApproveEnum.FUCK_FAIL.getCode());
            throw new BusinessException(PublicResultConstant.FRAGMENT_FAIL);
        }
    }


    /**
     * 添加一条我的申请 .
     * @param standardApprove .
     * @return .
     */
    @Override
    public StandardApprove addApprove(StandardApprove standardApprove,User user) {
        standardApprove.setUserNo(user.getUserNo());
        standardApprove.setApplyTime(new Date());
        standardApprove.setStatus(ApproveEnum.APPLYING.getCode());
        synUpdateItem(standardApprove.getStandardItemId(), ApproveEnum.APPLYING.getCode());
        return CommonUtil.isDBOpSuccess(standardApproveMapper.insert(standardApprove)) ? standardApprove : null;
    }

    //返回加水印后文件的位置
    private List<String> pdfToImgHandle(URL fileUrl, String dir) {
        return PDFToImage.pdfToImgUrl(1.5f, fileUrl, IMGPATH + dir + "/");
    }

    /**
     * 同步更新item表
     * @param itemId
     * @param status
     * @return
     */
    @Override
    public void synUpdateItem(int itemId, int status) {
        StandardItem item = itemMapper.selectById(itemId);
        item.setApproveStatus(status);
        itemMapper.updateById(item);
    }


    /**
     * 获取所有的申请 .
     * @param page .
     * @return .
     */
    public Page<StandardApprove> getAllApprove(Page<StandardApprove> page) {
        List<StandardApprove> standardApproveList = standardApproveMapper.selectPage(page, new EntityWrapper<StandardApprove>().orderBy("apply_time",false));

        for (StandardApprove standardApprove : standardApproveList) {
            standardApprove.setApplyUserName(userService.getUserByUserNo(standardApprove.getUserNo()).getUsername());
            standardApprove.setStandardItemNo(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandNo());
            standardApprove.setStandardItemName(standardItemService.getItemById(standardApprove.getStandardItemId()).getStandName());
            if (standardApprove.getApproveUserNo() != null) {
                standardApprove.setApproveUserName(userService.getUserByUserNo(standardApprove.getApproveUserNo()).getUsername());

            }
        }
        return page.setRecords(standardApproveList);
    }

    /**
     * 通过approveID获取User
     * @param id
     * @return
     */
    @Override
    public User getUserByAppId(int id) {
        StandardApprove approve = standardApproveMapper.selectById(id);
        return userService.getUserByUserNo(approve.getUserNo());
    }


}
